package com.useeinfo.oa.open.admin;

import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.DataCatBiz;
import com.useeinfo.oa.modules.base.biz.FacilityDataBiz;
import com.useeinfo.oa.modules.base.entity.DataCat;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.FacilityData;
import com.useeinfo.oa.modules.logger.biz.DataCatLogBiz;
import com.useeinfo.oa.modules.logger.entity.DataCatLog;
import com.useeinfo.oa.modules.logger.enums.LogTypeEnum;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: bin.liu
 * @Date: 2018/12/12 15:51
 * @Description: 设备分类action
 */
@Controller
@RequestMapping("/web/admin/dataCat")
public class DataCatManageAction {

    @Autowired
    private DataCatBiz dataCatBiz;

    @Autowired
    private FacilityDataBiz facilityDataBiz;

    @Autowired
    private DataCatLogBiz dataCatLogBiz;

    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/facilityData/dataCatList");
        return modelAndView;
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "searchCode", required = false) String searchCode,
                               @RequestParam(value = "orderBy", required = false) String orderBy,
                               HttpServletRequest request) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        queryParam.getSqlMap().put("searchCode", searchCode);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        if (StringUtils.isNotBlank(orderBy)) {
            queryParam.setSqlOrder("order by " + orderBy);
        }
        return dataCatBiz.findJSONList(queryParam);
    }


    @RequestMapping("/editPage")
    public ModelAndView editPage(@RequestParam(value = "id", required = false) String id,HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView();
        DataCat dataCat = dataCatBiz.findModel(StringConverters.ToLong(id));
        modelAndView.addObject("dataCat",dataCat);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        modelAndView.addObject("enterprise",enterprise);
        modelAndView.setViewName("pages/admin/facilityData/dataCatEdit");

        return modelAndView;
    }

    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public ResultDto addOrUpdate(DataCat dataCat) {
        dataCatBiz.addOrUpdate(dataCat);
        return ResultUtil.success();
    }

    /**
     * 执行提交的新增或修改请求
     */
    @RequestMapping("/executeDataCatEdit")
    @ResponseBody
    public ResultDto executeDataCatEdit(DataCat dataCat,
                                        @RequestParam(value = "createDate1", required = false) String createDate,
                                        HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("获取企业失败，请更新页面重试");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if(systemUser==null){
            return ResultUtil.error("获取用户信息失败，请更新页面重试");
        }
        if (dataCatBiz.existDataCatName(dataCat,enterprise.getId())) {
            return ResultUtil.error("您输入的类型名称为空或已存在，请重新输入");
        }
        if (StringUtils.isNotBlank(createDate)) {
            dataCat.setCreateDate(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", createDate));
        }
        dataCat.setEnterprise(enterprise);
        // 添加资料类型操作日志
        DataCatLog dataCatLog = new DataCatLog();
        if (dataCat.getId() == null) {
            dataCatLog.setLogTypeEnum(LogTypeEnum.insert);
            dataCatLog.setContent("新增资料类型：" + dataCat.getDataCatName());
        } else {
            dataCatLog.setLogTypeEnum(LogTypeEnum.update);
            dataCatLog.setContent("修改资料类型：" + dataCat.getDataCatName());
        }
        dataCatLog.setUserId(systemUser.getId());
        dataCatLog.setUserName(systemUser.getUserName());
        dataCatLog.setEnterpriseId(enterprise.getId());
        dataCatLog.setUserIp(request.getRemoteAddr());
        dataCatBiz.addOrUpdate(dataCat);
        dataCatLog.setDataCatId(dataCat.getId());
        dataCatLog.setDataCatName(dataCat.getDataCatName());
        dataCatLogBiz.addOrUpdate(dataCatLog);

        return ResultUtil.success();
    }

    /**
     * 获取系统模块选择数据
     *
     * @param q
     * @return
     */
    @RequestMapping("/getDataCatSelect")
    @ResponseBody
    public List<SelectVO> getDataCatSelect(@RequestParam(value = "q", required = false) String q, HttpServletRequest request) {
        List<SelectVO> selectVOS = new ArrayList<>();
        QueryParam queryParam = new QueryParam(1, 20);
        queryParam.getSqlMap().put("searchCode", q);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        List<DataCat> dataCatList = dataCatBiz.findList(queryParam);
        dataCatList.forEach(module -> selectVOS.add(new SelectVO(module.getDataCatName(), module.getId() + "")));
        return selectVOS;
    }

    /**
     * 逻辑删除设备资料分类信息
     */
    @RequestMapping("/logicRemoveDataCat")
    @ResponseBody
    public ResultDto logicRemoveFacilityGroup(@RequestParam(value = "id", required = false) String idParam,
                                              HttpServletRequest request) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if(systemUser==null){
            return ResultUtil.error("获取用户信息失败，请更新页面重试");
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("获取企业失败，请更新页面重试");
        }
        DataCat dataCat = dataCatBiz.findModel(StringConverters.ToLong(idParam));
        if (dataCat == null) {
            return ResultUtil.error("无此类型");
        }
        Long id = StringConverters.ToLong(idParam);
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("dataCatId",idParam);
        List<FacilityData> facilityDataList = facilityDataBiz.findList(queryParam);
        if(CollectionUtils.isNotEmpty(facilityDataList)){
            return ResultUtil.error("已关联数据,无法删除!");
        }

        // 添加资料类型操作日志
        DataCatLog dataCatLog = new DataCatLog();
        dataCatLog.setLogTypeEnum(LogTypeEnum.delete);
        dataCatLog.setContent("删除资料类型：" + dataCat.getDataCatName());
        dataCatLog.setUserId(systemUser.getId());
        dataCatLog.setUserName(systemUser.getUserName());
        dataCatLog.setEnterpriseId(enterprise.getId());
        dataCatLog.setUserIp(request.getRemoteAddr());
        dataCatLog.setDataCatId(StringConverters.ToLong(idParam));
        dataCatLog.setDataCatName(dataCat.getDataCatName());
        dataCatBiz.delete(id);
        dataCatLogBiz.addOrUpdate(dataCatLog);
        return ResultUtil.success();
    }
}
